package com.lxb.myforum.controller.admin.sysmgt

import javax.servlet.http.HttpServletRequest

import com.lxb.myforum.base.BaseController
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

import com.lxb.myforum.domain.PageResponse
import com.lxb.myforum.pojo.Dictionary
import com.lxb.myforum.service.DictionaryService

/**
 *
 * @author lxb
 */
@Controller("adminDictCtrl")
@RequestMapping("/admin/dicts")
class DictionaryController @Autowired
constructor(private val dictService: DictionaryService) : BaseController() {

    @GetMapping(value = ["/", ""])
    @Throws(Throwable::class)
    fun index(req: HttpServletRequest): String {
        val dictionary = dictService.findById(0L)
        req.setAttribute("rootDict", dictionary)
        return "/admin/sysmgt/dicts/index"
    }

    /**
     * 一般就是根据父id找子dictionary（直接子children）
     * @param dict
     * @return
     */
    @GetMapping(value = ["/all", "/list"])
    @ResponseBody
    fun dicts(dict: Dictionary, page: Int, size: Int): PageResponse<Dictionary> {
        val pr = PageRequest.of(page - 1, size)
        return dictService.findAll(dict, pr)
    }

    @GetMapping(value = ["/childNodes"])
    @ResponseBody
    fun childNodes(@RequestParam(value = "pId", defaultValue = "0") parentId: Long): List<Dictionary> {
        return dictService.findByPId(parentId)
    }

    @RequestMapping(value = ["", "/"], method = [RequestMethod.PUT, RequestMethod.POST])
    @ResponseBody
    fun saveDict(req: HttpServletRequest, @ModelAttribute dict: Dictionary): Dictionary? {
        return dictService.save(dict)
    }

    @GetMapping(value = ["/{id}", "/{id}/detail"])
    @ResponseBody
    @Throws(Throwable::class)
    fun detail(@PathVariable("id") id: Long): Dictionary {
        return dictService.findById(id)
    }

    @DeleteMapping(value = ["/{id}"])
    @ResponseBody
    fun delDict(@PathVariable("id") id: Long): Map<String, Any> {
        return dictService.deleteById(id)
    }
}
